//package com.example.floatingpopulation.utils;
//
//import cn.hutool.core.date.DateUtil;
//import cn.hutool.core.util.StrUtil;
//import com.auth0.jwt.JWT;
//import com.auth0.jwt.algorithms.Algorithm;
//import com.example.floatingpopulation.entity.Admin;
//import com.example.floatingpopulation.service.AdminService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import java.util.Date;
//
//@Component
//@Slf4j
//public class TokenUtils {
//
//    private static AdminService staticAdminService;
//
//    @Resource
//    private AdminService adminService;
//
//    @PostConstruct
//    public void setUserService() {
//        staticAdminService = adminService;
//    }
//
//    /**
//     * 生成token
//     *
//     * @return
//     */
//    public static String genToken(String adminId, String sign) {
//        return JWT.create().withAudience(adminId) // 将 adminId 保存到 token 里面,作为载荷
//                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
//                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
//    }
//    /**
//     * 获取当前登录的用户信息
//     *
//     * @return admin对象
//     *  /admin?token=xxxx
//     */
//    public static Admin getCurrentAdmin() {
//        String token = null;
//        try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            token = request.getHeader("token");
//            if (StrUtil.isNotBlank(token)) {
//                token = request.getParameter("token");
//            }
//            if (StrUtil.isBlank(token)) {
//                log.error("获取当前登录的token失败， token: {}", token);
//                return null;
//            }
//            String adminId = JWT.decode(token).getAudience().get(0);
//            return staticAdminService.getById(Integer.valueOf(adminId));
//        } catch (Exception e) {
//            log.error("获取当前登录的管理员信息失败, token={}", token,  e);
//            return null;
//        }
//    }
//}
//
package com.example.floatingpopulation.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.floatingpopulation.entity.Admin;
import com.example.floatingpopulation.entity.User;
import com.example.floatingpopulation.service.AdminService;
import com.example.floatingpopulation.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Slf4j
public class TokenUtils {

    private static AdminService staticAdminService;
    private static UserService staticUserService;

    @Resource
    private AdminService adminService;
    @Resource
    private UserService userService;

    @PostConstruct
    public void setServices() {
        staticAdminService = adminService;
        staticUserService = userService;
    }

    /**
     * 生成token
     *
     * @param userId 用户ID
     * @param sign   签名密钥
     * @return 生成的token
     */
    public static String genToken(String userId, String sign) {
        return JWT.create().withAudience(userId) // 将 userId 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return 用户对象，可以是 Admin 或 User
     */
    public static Object getCurrentUser() {
        String token = null;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getHeader("token");
            if (StrUtil.isBlank(token)) {
                token = request.getParameter("token");
            }
            if (StrUtil.isBlank(token)) {
                log.error("获取当前登录的token失败， token: {}", token);
                return null;
            }
            String userId = JWT.decode(token).getAudience().get(0);
            // 假设 userId 前缀为 "A" 表示 Admin，前缀为 "U" 表示 User
            if (userId.startsWith("A")) {
                return staticAdminService.getById(Integer.valueOf(userId.substring(1)));
            } else if (userId.startsWith("U")) {
                return staticUserService.getById(Integer.valueOf(userId.substring(1)));
            } else {
                log.error("无法识别的用户类型，userId: {}", userId);
                return null;
            }
        } catch (Exception e) {
            log.error("获取当前登录的用户信息失败, token={}", token, e);
            return null;
        }
    }
}
